package com.xiaoran.robot.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONValidator;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.*;

public class DictsParser {
    private static HashMap<List<String>, String> flattenDicts = new HashMap<>();
    private static final String baseClassP = "com.xiaoran.robot.customHandler.";
    public DictsParser(Integer type){
        flattenDicts.clear();
        // type => 1 无需触发条件
        String dictsPath;
        if(type == 1){
            dictsPath = YamlReader.instance.getValueByKey("mirai.dictsAPath").toString();

        } else {
            dictsPath = YamlReader.instance.getValueByKey("mirai.dictsBPath").toString();
        }
        flattenDicts = this.loadDicts(dictsPath);
    }
    public HashMap<List<String>, String> loadDicts(String dicts) {
        String s;
        try {
            s = FileUtils.readFileToString(new File(dicts), "utf-8");
            JSONObject data = StringUtils.toJson(s);
            flattenDicts(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flattenDicts;
    }

    /**
     * 解析多级 json数据成一维的 key => val
     */
    public void flattenDicts(JSONObject data) {
        Set<String> keys = data.keySet();
        List<String> listItems = new ArrayList<>();
        for (String item : keys) {
            boolean isMutiKey = false;
            // 将 item 以-分开生成Array
            if(item.contains("-")){
                String[] splitItem = item.split("-");
                listItems = Arrays.asList(splitItem);
                isMutiKey = true;
            }
            String sub = data.getString(item);
            boolean validate = JSONValidator.from(sub).validate();
            if (validate) {
                JSONObject jsonObject = JSON.parseObject(sub);
                Set<String> keys1 = jsonObject.keySet();
                StringBuilder s = new StringBuilder();
                for (String item1 : keys1) {
                    s.append(item1).append("\n");
                }
                if(isMutiKey) {
                    flattenDicts.put(listItems, s.toString());
                }else{
                    flattenDicts.put(Collections.singletonList(item), s.toString());
                }
                flattenDicts(jsonObject);
            } else {
                if(isMutiKey){
                    flattenDicts.put(listItems, sub);
                }else {
                    flattenDicts.put(Collections.singletonList(item), sub);
                }
            }
        }
    }

    /**
     * 根据 key返回对应的 val，并且根据 val的类型进行处理,所以返回的 val可能是图片，也可能是简单的文本，或者其他。
     */
    @SuppressWarnings("unchecked")
    public ArrayList<Object> getVal(String key, String type, String qq){
        ArrayList<Object> rst = new ArrayList<>();
        String s = "";
        Set<List<String>> lists = flattenDicts.keySet();
        for (List<String> list : lists) {
            if (list.contains(key)) {
                s = flattenDicts.get(list);
                break;
            }
        }
        if (s.contains("#") && s.replaceFirst("#", "").contains("#")) {
            // 交给对应类处理
            int i = s.indexOf("#") + 1;
            int j = s.lastIndexOf("#");
            String className = s.substring(i, j);
            try {
                Class<?> clazz = Class.forName(baseClassP + className);
                Object instance = clazz.getDeclaredConstructor().newInstance();
                rst = (ArrayList<Object>) clazz.getMethod("result").invoke(instance);
            } catch (ClassNotFoundException e) {
                System.out.println("没有找到可以解析" + baseClassP + className + "的类");
                e.printStackTrace();
            } catch (Exception e) {
                // IllegalAccessException | NoSuchMethodException | InstantiationException | InvocationTargetException
                e.printStackTrace();
            }
        } else {
            if ("group".equals(type)) {
                rst = new RstMsgUtils().atQQ(qq).addText("\n").addText(s).build();
            } else {
                rst = new RstMsgUtils().addText(s).build();
            }
        }
        return rst;
}
    /**
     * 是否包含指定的 key
     */
    public boolean containsKey(String key){
        boolean status = false;
        Set<List<String>> lists = flattenDicts.keySet();
        for (List<String> list : lists) {
            if(list.contains(key)){
                status = true;
                break;
            }
        }
        return status;
    }
}
